var params = {
  left: 0,
  top: 0,
  currentX: 0,
  currentY: 0,
  flag: false
};
// 获取相关CSS属性
var getCss = function(o, key) {
  return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, false)[key];
};
// 拖拽的实现
var startDrag = function(bar, target, callback) {
  if (getCss(target, "left") !== "auto") {
    params.left = getCss(target, "left");
  }
  if (getCss(target, "top") !== "auto") {
    params.top = getCss(target, "top");
  }
  // o是移动对象
  bar.onmousedown = function(event) {
    params.flag = true;
    if (!event) {
      event = window.event;
      // 防止IE文字选中
      bar.onselectstart = function() {
        return false;
      }
    }
    var e = event;
    params.currentX = e.clientX;
    params.currentY = e.clientY;
  };
  document.onmouseup = function() {
    params.flag = false;
    if (getCss(target, "left") !== "auto") {
      params.left = getCss(target, "left");
    }
    if (getCss(target, "top") !== "auto") {
      params.top = getCss(target, "top");
    }
  };
  document.onmousemove = function(event) {
    var e = event || window.event;
    if (params.flag) {
      var nowX = e.clientX;

      var nowY = e.clientY;
      var disX = nowX - params.currentX;

      var disY = nowY - params.currentY;
      target.style.left = parseInt(params.left) + disX + "px";
      target.style.top = parseInt(params.top) + disY + "px";
    }
    //		        if(getNum(target.style.left) > 0){
    //		        	target.style.left = "0px";
    //		        }
    //		        if(getNum(target.style.top) > 0){
    //			        target.style.top = "0px";
    //		        }
    if (typeof callback === "function") {
      callback(parseInt(params.left) + disX, parseInt(params.top) + disY);
    }
  }
};

const change = function() {
  var oBox = document.getElementById("dragbox");
  var oBar = document.getElementById("dragbar");
  startDrag(oBar, oBox);
}

function getNum(string) {
  var reg = /^\d$/;
  var num = "";
  for (var i = 0; i < string.length; i++) {
    if (reg.test(string[i])) {
      num = num + string[i]
    }
  }
  return Number(num)
}
export default change
